$(document).ready(function() {
	UserMessages.init();
});

UserMessages = {};

UserMessages.init = function() {
	$("#userMessagesTabs").tabs();

	$('.userMessagesTable').bind('click', function(e) {
		if($(e.target).prop("tagName") != 'A' && $(e.target).prop("tagName") != 'a'){
			var conversationContainer = $(this).closest('.userMessagesPrivateContainer');
			var messageListContainer = conversationContainer.find('#messageListContainer');
			var unreadIdInput = conversationContainer.find('#unreadIds');
			var jumpId = conversationContainer.find('#jumpId').val();
			
			if(messageListContainer.css('display') == 'none'){
				messageListContainer.css('display', 'block');
				if(unreadIdInput.val() != ''){
					UserMessages.markRead(unreadIdInput.val());
					unreadIdInput.val('');
				}
			}else{
				messageListContainer.css('display', 'none');
			}     
			
			if(jumpId != ''){
				location.hash = '';
				location.hash = '#message-'+jumpId;
			}
		}  
	});
	
	$('.sendPrivateMessageButton').bind('click', function(e) {
		var form = $(this).closest('form');
		var messageContentInput = form.find('#messageContent');
		
		var recipientId = form.find('#recipientId').val();
		var messageContent = messageContentInput.val().replace(/&/g, '&amp;').replace(/</g, '&lt;')
		                                              .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
		
		if(messageContent.trim() != ''){
			var template = UserMessages.addTemplate(form, messageContent);
			var successFunc = function(jsonData){
				$('#randomKeyInput').val(jsonData.randomKey);
				if (jsonData.status == 'success') {
					template.find('#status').attr('class', 'userMessagesAjaxCheck');
				} else {
					template.find('#status').attr('class', 'userMessagesAjaxError');
				}
			}
			var failFunc = function(){
				template.find('#status').attr('class', 'userMessagesAjaxError');
			}
			UserMessages.sendPrivateAnswer(recipientId, messageContent, successFunc, failFunc);
			messageContentInput.val('');
		}		
		
		return false;
	});
	
	$('.sendPrivateMessageExtButton').bind('click', function(e) {
		var form = $(this).closest('form');
		var messageContentInput = form.find('#messageContent');
		
		var partnerId = form.find('#partnerId').val();
		var extUserId = form.find('#extUserId').val();
		var extUserName = form.find('#extUserName').val();
		var extConversationId = form.find('#extConversationId').val();
		
		var recipientId = form.find('#recipientId').val();
		var messageContent = messageContentInput.val().replace(/&/g, '&amp;').replace(/</g, '&lt;')
		                                              .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
		
		if(messageContent.trim() != ''){
			var template = UserMessages.addTemplate(form, messageContent);
			var successFunc = function(jsonData){
				$('#randomKeyInput').val(jsonData.randomKey);
				if (jsonData.status == 'success') {
					template.find('#status').attr('class', 'userMessagesAjaxCheck');
				} else {
					template.find('#status').attr('class', 'userMessagesAjaxError');
				}
			}
			var failFunc = function(){
				template.find('#status').attr('class', 'userMessagesAjaxError');
			}
			UserMessages.sendPrivateAnswerExt(recipientId, partnerId,
					messageContent, successFunc, failFunc, extUserId,
					extUserName, extConversationId);
			messageContentInput.val('');
		}		
		
		return false;
	});
	
	/*
	 * Item Message
	 */
	$('.sendItemMessageButton').bind('click', function(e) {
		var form = $(this).closest('form');
		var messageContentInput = form.find('#messageContent');
		
		var recipientId = form.find('#recipientId').val();
		var itemId = form.find('#itemId').val();
		var messageContent = messageContentInput.val();
		
		if(messageContent.trim() != ''){
			var template = UserMessages.addTemplate(form, messageContent);
			var successFunc = function(jsonData){
				$('#randomKeyInput').val(jsonData.randomKey);
				if (jsonData.status == 'success') {
					template.find('#status').attr('class', 'userMessagesAjaxCheck');
				} else {
					template.find('#status').attr('class', 'userMessagesAjaxError');
				}
			}
			var failFunc = function(){
				template.find('#status').attr('class', 'userMessagesAjaxError');
			}
			UserMessages.sendItemAnswer(recipientId, messageContent, itemId, successFunc, failFunc);
			messageContentInput.val('');
		}		
		
		return false;
	});
	
	$('.sendItemMessageExtButton').bind('click', function(e) {
		var form = $(this).closest('form');
		var messageContentInput = form.find('#messageContent');
		
		var recipientId = form.find('#recipientId').val();
		
		var partnerId = form.find('#partnerId').val();
		var extUserId = form.find('#extUserId').val();
		var extUserName = form.find('#extUserName').val();
		var extConversationId = form.find('#extConversationId').val();
		
		var itemId = form.find('#itemId').val();
		var messageContent = messageContentInput.val();
		
		if(messageContent.trim() != ''){
			var template = UserMessages.addTemplate(form, messageContent);
			var successFunc = function(jsonData){
				$('#randomKeyInput').val(jsonData.randomKey);
				if (jsonData.status == 'success') {
					template.find('#status').attr('class', 'userMessagesAjaxCheck');
				} else {
					template.find('#status').attr('class', 'userMessagesAjaxError');
				}
			}
			var failFunc = function(){
				template.find('#status').attr('class', 'userMessagesAjaxError');
			}
			UserMessages.sendItemAnswerExt(recipientId, partnerId,
					itemId, messageContent, successFunc, failFunc,
					extUserId, extUserName, extConversationId);
			messageContentInput.val('');
		}		
		
		return false;
	});
	
	/*
	 * Multi Message
	 */
	$('.sendMultiMessageButton').bind('click', function(e) {
		var messageContent = $('#multiMessageContent').val();
		
		if(messageContent.trim() != '' && UserMessages.recipientList.length > 0){
			var successFunc = function(jsonData){
				$('#randomKeyInput').val(jsonData.randomKey);
				if (jsonData.status == 'success') {
					$('#multiMessageStatus').attr('class', 'userMessagesAjaxCheck');
				} else {
					$('#multiMessageStatus').attr('class', 'userMessagesAjaxError');
				}
			}
			var failFunc = function(){
				$('#multiMessageStatus').attr('class', 'userMessagesAjaxError');
			}
			UserMessages.sendMultiMessage(messageContent, successFunc, failFunc);
			$('#multiMessageContent').val('');
			var l = UserMessages.recipientList.length;
			for(var i = 0; i < l; i++){
				UserMessages.removeRecipient(UserMessages.recipientList[0]);
			}
		}		
		return false;
	});
	
	if(location.hash != ''){
		location.hash = '';
		/*
		var jumpElement = location.hash;
		var element = $(jumpElement);
		if(element.size() > 0){
			var messageListContainer = element.closest('.userMessagesPrivateContainer').find('#messageListContainer');
			messageListContainer.css('display', 'block');
			location.hash = '';
			location.hash = jumpElement;
		}
		*/
	}
	

	$("#recipientInput").autocomplete({
		source : "/ajax/usernameSearch",
		minLength : 2,
		select : function(event, ui) {
			$("#recipientInput").val('');
			UserMessages.addRecipient(ui.item.id, ui.item.value);
			return false;
		}
	});
}

UserMessages.sendPrivateAnswer = function(recipient, text, successFunc, failFunc) {
	var link = '/ajax/messageService/sendMessage';
	$.ajax({
		url : link,
		type : "POST",
		data : {
			randomKey: $('#randomKeyInput').val(),
			recipient : recipient,
			message : text
		},
		dataType : "json"
	}).done(successFunc).fail(failFunc);
}

UserMessages.sendItemAnswer = function(recipient, text, itemId, successFunc, failFunc) {
	var link = '/ajax/messageService/sendMessage';
	$.ajax({
		url : link,
		type : "POST",
		data : {
			randomKey: $('#randomKeyInput').val(),
			recipient : recipient,
			message : text,
			item: itemId
		},
		dataType : "json"
	}).done(successFunc).fail(failFunc);
}

UserMessages.sendPrivateAnswerExt = function(recipient, partner, text, successFunc, failFunc, extUserId, extUserName, extConversationId) {
	var link = '/ajax/messageService/sendMessageExt';
	$.ajax({
		url : link,
		type : "POST",
		data : {
			randomKey: $('#randomKeyInput').val(),
			
			extConversationId:extConversationId,
			extUserId:extUserId,
			extUserName:extUserName,
			
			recipient : recipient,
			partner : partner,
			message : text
		},
		dataType : "json"
	}).done(successFunc).fail(failFunc);
}

UserMessages.sendItemAnswerExt = function(recipient, partner, itemId, text, successFunc, failFunc, extUserId, extUserName, extConversationId) {
	var link = '/ajax/messageService/sendMessageExt';
	$.ajax({
		url : link,
		type : "POST",
		data : {
			randomKey: $('#randomKeyInput').val(),
			
			extConversationId:extConversationId,
			extUserId:extUserId,
			extUserName:extUserName,
			
			item: itemId,
			recipient : recipient,
			partner : partner,
			message : text
		},
		dataType : "json"
	}).done(successFunc).fail(failFunc);
}

UserMessages.markRead = function(unreadIds) {
	var link = '/ajax/messageService/markRead';
	$.ajax({
		url : link,
		type : "POST",
		data : {
			ids : unreadIds
		},
		dataType : "json"
	});
}

UserMessages.sendMultiMessage = function(messageContent, successFunc, failFunc) {
	var link = '/ajax/messageService/sendMultiMessage';
	$.ajax({
		url : link,
		type : "POST",
		data : {
			recipients : UserMessages.recipientList,
			randomKey: $('#randomKeyInput').val(),
			message : messageContent
		},
		dataType : "json"
	}).done(successFunc).fail(failFunc);
}

UserMessages.addTemplate = function(form, text) {
	var template = form.find('#messageTemplate').clone();
	template.attr('class', 'userMessagesPrivateMessage');
	template.find('#text').html(text.replace(/\n/g, "<br>"));
	form.before(template);
	return template;
}

UserMessages.recipientList = new Array();

UserMessages.addRecipient = function(userid, username) {
	if($.inArray(userid, UserMessages.recipientList)==-1){
		UserMessages.recipientList.push(userid);
		$('#recipientList').append('<div style="padding:2px; cursor:pointer;" id="recipient-'+userid+'"><img style="vertical-align: middle;" src="/images/icons/user_gray.png"><span style="padding-left: 5px;">'+username+'</span></div>');
		$('#recipient-'+userid).bind('click', function(){UserMessages.removeRecipient(userid)});
	}
}

UserMessages.removeRecipient = function(userid) {
	UserMessages.recipientList.splice( $.inArray(userid , UserMessages.recipientList), 1 );
	$('#recipient-'+userid).remove();
}